package com.yanfan.energy.service.impl;


import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.domain.model.LoginUser;
import com.yanfan.common.utils.SecurityUtils;
import com.yanfan.energy.domain.*;
import com.yanfan.energy.domain.enums.BillTypeEnums;
import com.yanfan.energy.domain.enums.OrderTypeEnums;
import com.yanfan.energy.domain.enums.WorkOrderStatus;
import com.yanfan.energy.mapper.AssignmentTemplateTaskDao;
import com.yanfan.energy.mapper.DispatchListDao;
import com.yanfan.energy.mapper.ProductionDictDao;
import com.yanfan.energy.service.DispatchListService;
import com.yanfan.energy.util.DateUtils;
import com.yanfan.energy.util.SerialNumberUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 工单表(DispatchList)表服务实现类
 *
 * @author makejava
 * @since 2023-01-11 13:49:19
 */
@Service("dispatchListService")
@Transactional(rollbackFor = Exception.class)
public class DispatchListServiceImpl implements DispatchListService {
    @Resource
    private DispatchListDao dispatchListDao;

    @Resource
    private ProductionDictDao productionDictDao;

    @Resource
    private AssignmentTemplateTaskDao assignmentTemplateTaskDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public DispatchList queryById(Long id) {
        DispatchList dispatchList = this.dispatchListDao.queryById(id);
        if (dispatchList == null) {
            return null;
        }
        dispatchList.setStateName(WorkOrderStatus.getEnumByType(dispatchList.getState()));
        dispatchList.setMatterName(questionTypeMap().get(dispatchList.getMatterType()));
        if (dispatchList.getType() != null) {
            dispatchList.setTypeName(OrderTypeEnums.getEnumByType(Long.valueOf(dispatchList.getType())));
        }
        DispatchPicture picture = new DispatchPicture();
        picture.setNumber(dispatchList.getId());
        picture.setType(BillTypeEnums.WORK_ORDER.getCode());

        dispatchList.setPictureList(dispatchListDao.queryByNumber(picture));
        DispatchList dispatch = dispatchListDao.queryRelationInfo(dispatchList);
        if (dispatch != null) {
            dispatchList.setBatches(dispatch.getBatches());
            dispatchList.setSegments(dispatch.getSegments());
            dispatchList.setWorkshopName(dispatch.getWorkshopName());
            dispatchList.setPlantName(dispatch.getPlantName());
        }
        if (dispatchList.getTemplateId() != null) {
            dispatchList.setTasks(assignmentTemplateTaskDao.queryTasksByDispatchList(dispatchList));
        }

        return dispatchList;
    }

    /**
     * 分页查询
     *
     * @param dispatchList 筛选条件
     * @return 查询结果
     */
    @Override
    public List<DispatchList> queryByPage(DispatchList dispatchList) {
        // 是管理员
        if (dispatchList.getMobileFlag() != null && dispatchList.getMobileFlag() && SecurityUtils
                .getLoginUser()
                .getUser()
                .isAdmin()) {
//            dispatchList.setConductor(SecurityUtils.getLoginUser().getUserId());
        }
        List<DispatchList> dispatchLists = dispatchListDao.queryAllByLimit(dispatchList);
        Map<Long, String> queMap = questionTypeMap();
        if (!CollectionUtils.isEmpty(dispatchLists)) {
            for (DispatchList dispatch : dispatchLists) {
                dispatch.setStateName(WorkOrderStatus.getEnumByType(dispatch.getState()));
                dispatch.setMatterName(queMap.get(dispatch.getMatterType()));

                if (dispatch.getType() != null) {
                    dispatch.setTypeName(OrderTypeEnums.getEnumByType(Long.valueOf(dispatch.getType())));
                }
            }
        }
        return dispatchLists;
    }

    /**
     * 分页查询
     *
     * @param dispatchList 筛选条件
     * @return 查询结果
     */
    @Override
    public List<DispatchListHead> queryByPageReport(DispatchList dispatchList) {
        return dispatchListDao.queryByPageReport(dispatchList);
    }

    /**
     * 新增数据
     *
     * @param dispatchList 实例对象
     * @return 实例对象
     */
    @Override
    public DispatchList insert(DispatchList dispatchList) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 事件类型编号
        dispatchList.setTypeNumber(dispatchList.getNumber());
        dispatchList.setNumber(SerialNumberUtil.createDispatchNo());
        dispatchList.setCreatedBy(String.valueOf(loginUser.getUserId()));
        dispatchList.setCreatedDate(new Date());
        dispatchList.setLastModifiedDate(new Date());
        // 处理人工号
        dispatchList.setCreator(loginUser.getUserId());
        dispatchList.setAddDate(new Date());
        dispatchList.setState(1L);
        this.dispatchListDao.insert(dispatchList);
        // number 为工单ID ，但是ID没有生成
        List<DispatchPicture> pictureList = dispatchList.getPictureList();
        if (!CollectionUtils.isEmpty(pictureList)) {
            for (DispatchPicture dispatchPicture : pictureList) {
                dispatchPicture.setNumber(dispatchList.getId());
                dispatchPicture.setType(BillTypeEnums.WORK_ORDER.getCode());
                dispatchPicture.setCreatedBy(loginUser.getUsername());
                dispatchPicture.setCreatedDate(new Date());
            }
            dispatchListDao.dispatchPictureAdd(pictureList);
        }

        return dispatchList;
    }

    /**
     * 修改数据
     *
     * @param dispatchList 实例对象
     * @return 实例对象
     */
    @Override
    public DispatchList update(DispatchList dispatchList) {
        dispatchList.setLastModifiedDate(new Date()); // 最后修改时间
        dispatchList.setTypeNumber(dispatchList.getNumber());
        dispatchList.setNumber(null);// 工单编号 不允许修改
        this.dispatchListDao.update(dispatchList);
        // 查询数据库所有的图片信息
        DispatchPicture picture = new DispatchPicture();
        picture.setNumber(dispatchList.getId());
        picture.setType(0);
        List<Long> ids = dispatchListDao.queryPictureIds(picture);
        List<DispatchPicture> pictureList = dispatchList.getPictureList();
        if (!CollectionUtils.isEmpty(pictureList)) {
            for (DispatchPicture dispatchPicture : pictureList) {
                dispatchPicture.setNumber(dispatchList.getId());
                dispatchPicture.setType(BillTypeEnums.WORK_ORDER.getCode());
            }
            dispatchListDao.dispatchPictureInsertOrUpdate(pictureList);
            // 提出
            if (!CollectionUtils.isEmpty(ids)) {
                for (DispatchPicture dispatchPicture : pictureList) {
                    if (dispatchPicture.getId() != null) {
                        ids.remove(dispatchPicture.getId());
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(ids)) {
            dispatchListDao.deletePictureIds(ids);
        }

        return this.queryById(dispatchList.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.dispatchListDao.deleteById(id) > 0;
    }

    @Override
    public List<ProductionDict> questionType() {
        ProductionDict p = new ProductionDict();
        p.setType(1L);
        return productionDictDao.queryAll(p);
    }

    public Map<Long, String> questionTypeMap() {
        List<ProductionDict> productionDicts = questionType();
        Map<Long, String> resMap = new HashMap<>();
        if (CollectionUtils.isEmpty(productionDicts)) {
            return resMap;
        }
        for (ProductionDict productionDict : productionDicts) {
            resMap.put(productionDict.getId(), productionDict.getName());
        }
        return resMap;
    }


    @Override
    public List<BaseOrderEntity> queryOddNumbers(Integer type) {
        return productionDictDao.queryOddNumbers(type);
    }

    @Override
    public List<BaseOrderEntity> queryOddTypes() {
        List<BaseOrderEntity> list = new ArrayList<BaseOrderEntity>();
        list.add(BaseOrderEntity.builder().id(1L).name("订单号").build());
        list.add(BaseOrderEntity.builder().id(2L).name("批次号").build());
        list.add(BaseOrderEntity.builder().id(3L).name("分段号").build());
        return list;
    }

    @Override
    public AjaxResult taskStart(Long id) {
        DispatchList dispatchList = this.dispatchListDao.queryById(id);
        if (dispatchList == null) {
            return AjaxResult.error("该工单不存在");
        }
        dispatchList.setState(2L);
        dispatchList.setFactBeginTime(new Date());
        dispatchListDao.update(dispatchList);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult taskFinish(DispatchList req) {
        DispatchList dispatchList = this.dispatchListDao.queryById(req.getId());
        if (dispatchList == null) {
            return AjaxResult.error("该工单不存在，或者该任务状态不为“处理中”");
        }
        // 查询数据库所有的图片信息
        DispatchPicture picture = new DispatchPicture();
        picture.setNumber(dispatchList.getId());
        picture.setType(0);
        List<Long> ids = dispatchListDao.queryPictureIds(picture);
        List<DispatchPicture> pictureList = req.getPictureList();
        if (!CollectionUtils.isEmpty(pictureList)) {
            for (DispatchPicture dispatchPicture : pictureList) {
                dispatchPicture.setType(BillTypeEnums.WORK_ORDER.getCode());
                dispatchPicture.setNumber(dispatchList.getId());
            }
            dispatchListDao.dispatchPictureInsertOrUpdate(pictureList);
            // 提出
            if (!CollectionUtils.isEmpty(ids)) {
                for (DispatchPicture dispatchPicture : pictureList) {
                    if (dispatchPicture.getId() != null) {
                        ids.remove(dispatchPicture.getId());
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(ids)) {
            dispatchListDao.deletePictureIds(ids);
        }

        // 任务相关
        List<AssignmentTemplateTask> tasks = req.getTasks();
        /*DispatchList dataBase = queryById(req.getId());
        List<AssignmentTemplateTask> taskDataBaseList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(tasks)){
            taskDataBaseList = dataBase.getTasks();
        }*/
        // 任务项已完成 不为空
        if (!CollectionUtils.isEmpty(tasks)) {
            assignmentTemplateTaskDao.updateTaskState(tasks);
        }
        // 任务项不为空，且任务项和数据库相同
        // 任务为已完成
        Date now = new Date();
        dispatchList.setState(3L);
        dispatchList.setFactEndTime(now);
        dispatchList.setFactHour(DateUtils.diff(dispatchList.getFactBeginTime(), now));
        dispatchListDao.update(dispatchList);
        return AjaxResult.success();
    }

}
